﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlashCards.WebApp.Utils;
using FlashCards.WebApp.Models;
using FlashCards.Model;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using FlashCards.WebApp.DataAccessLayer;

namespace FlashCards.WebApp.Controllers
{
    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            var categories = CategoriesUtils.GetAllCategories();
            var users = UserUtils.GetUsersOrderByLastLoginDate();
            var model = new AdminModel(categories, users);

            //using (var context = new FlashCardsEntities())
            //{
            //    var img = Image.FromFile("D:\\User-Green.jpg");
            //    var stream = new MemoryStream();
            //    img.Save(stream, ImageFormat.Jpeg);

            //    var avatar = new Avatar() { Data = stream.ToArray() };
            //    context.Avatars.AddObject(avatar);

            //    context.SaveChanges();
            //}


            return View(model);
        }

        public ActionResult AddCategory()
        {
            var categories = CategoriesUtils.GetAllCategories();
            var model = new AddCategoryModel(categories);
            return View(model);
        }

        [HttpPost]
        public ActionResult AddCategory(FormCollection form)
        {
            var name = form["name"];
            var parentIdString = form["SelectedItemId"];
            if(!string.IsNullOrEmpty(name))
            {
                if (!string.IsNullOrEmpty(parentIdString))
                {
                    var id = int.Parse(parentIdString);
                    CategoriesUtils.AddCategory(name, id);
                }
                else
                    CategoriesUtils.AddCategory(name);
            }
            return RedirectToAction("Index");
        }

        public ActionResult DeleteCategory(int categoryId)
        {
            if (categoryId != 0)
            {
                CategoriesUtils.DeleteCategory(categoryId);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult AddNews(FormCollection form)
        {
            var title = form["NewsTitle"];
            var message = form["NewsMessage"];

            if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(message))
            {
                DevelopmentNewsUtils.AddNews(title, message);
            }

            return RedirectToAction("Index");
        }
    }
}
